﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StudentInfo;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace Ex_17._3_Output_StudentInfo
{
    public partial class OutputStudentInfoForm : StudentInfoUIForm
    {
        public OutputStudentInfoForm()
        {
            InitializeComponent();
        }

        private BinaryFormatter reader = new BinaryFormatter();
        private FileStream input;

        private void openButton_Click(object sender, EventArgs e)
        {
            DialogResult result;
            string fileName;

            using (OpenFileDialog fileChooser = new OpenFileDialog())
            {
                result = fileChooser.ShowDialog();
                fileName = fileChooser.FileName;
            }

            if (result == DialogResult.OK)
            {
                if (fileName == string.Empty)
                {
                    MessageBox.Show("Invalid file name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    input = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                    TextBoxesEnabled(true);
                    openButton.Enabled = false;
                    nextButton.Enabled = true;
                }
            }
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            try
            {
                Student student = (Student) reader.Deserialize(input);

                string[] values = new string[]
                    {
                        student.FirstName,
                        student.LastName,
                        student.ID.ToString(),
                        student.StudentClass,
                        student.Grade
                    };

                SetTextBoxValues(values);
            }
            catch (SerializationException)
            {
                input.Close();
                TextBoxesEnabled(false);
                openButton.Enabled = true;
                nextButton.Enabled = false;

                ClearTextBoxes();

                MessageBox.Show("No more students in file", string.Empty, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        private void OutputStudentInfoForm_Load(object sender, EventArgs e)
        {
            TextBoxesEnabled(false);
        }
    }
}
